package com.lvyou.config;

import com.lvyou.intercepter.AdminLoginInter;
import com.lvyou.intercepter.UserLoginInter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Value("${file.url}")
    private String fileUrl;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //注意：最后要以 / 结尾，否则配置的映射路径不可用
        registry.addResourceHandler(fileUrl+"**").addResourceLocations("file:"+uploadFolder);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> notFilterPath=new ArrayList();
        notFilterPath.add("/mgr/js/**");//支持通配符*
        notFilterPath.add("/mgr/css/**");
        notFilterPath.add("/mgr/images/**");
        notFilterPath.add("/mgr/login.html");
        notFilterPath.add("/mgr/doLogin");
        notFilterPath.add("/mgr/");
        notFilterPath.add("/mgr/show*.html");

        registry.addInterceptor(new AdminLoginInter())
                .addPathPatterns("/mgr/**")
                .excludePathPatterns(notFilterPath);



        List<String> notUserAuthInterPath=new ArrayList();

        notUserAuthInterPath.add("/js/**");//支持通配符*
        notUserAuthInterPath.add("/css/**");
        notUserAuthInterPath.add("/login.html");
        notUserAuthInterPath.add("/doLogin");

        registry.addInterceptor(new UserLoginInter())
                .addPathPatterns("/order/**")
                .excludePathPatterns(notUserAuthInterPath);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")//匹配Controller RequestMapping
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}
